const http = require('http')
const Router = require('./router')

function App() {
  this.router = new Router()
}

App.prototype.get = function (path, handler) {
  this.router.add(path, 'get', handler)
}

App.prototype.post = function (path, handler) {
  this.router.add(path, 'post', handler)
}


App.prototype.listen = function (...args) {
  http.createServer((req, res) => {
    // 可以自动适配响应体的数据
    res.send = function (data) {
      if (typeof data == 'object') {
        if ((data instanceof Object || Array.isArray(data)) && !(data instanceof Buffer)) {
          res.setHeader('content-type', 'application/json;charset=utf-8')
          res.end(JSON.stringify(data))
        } else {
          res.setHeader('content-type', 'text/html;charset=utf-8')
          res.end(data)
        }
      } else if (typeof data == 'string') {
        res.setHeader('content-type', 'text/html;charset=utf-8')
        res.end(data)
      } else {
        res.end(data + '')
      }
    }

    const done = () => {
      res.send('没有处理的数据')
    }

    this.router.matchRoute(req, res, done)
  }).listen(...args)
}

module.exports = App